package com.anyisn.anyflickr.shell.model
{
	import com.adobe.webapis.flickr.PagedPhotoList;
	import com.adobe.webapis.flickr.Photo;
	import com.anyisn.flickr.as3.patterns.proxy.FlickrPhotoProxy;
	import com.elad.framework.utils.ReadDirectoryHelper;
	
	import flash.events.Event;
	import flash.filesystem.File;
	
	import mx.controls.Alert;
	
	public class PhotoProxy extends FlickrPhotoProxy
	{
		public static const NAME:String = 'PhotoProxy';
		private var _url:String;
		public var hasPIWin:Boolean;
		
		public function PhotoProxy(data:Object=null)
		{
			super(NAME, data);
			hasPIWin = false;
		}
		
		public function prepareDownload(photo:Photo):void {
			currentPhoto = photo;
			getSizes(photo.id);
		}
		
		public function download(url:String) : void {
			_url =  url;
			if(downloadPath) {
				var results:Array = url.split("/");
				var fileName:String = results[results.length-1];
				var array:Array = ReadDirectoryHelper.getDirectoryFiles(downloadPath);
				var isExists:Boolean = ReadDirectoryHelper.isFileExists(array, fileName);
				if (isExists == false) {
					var directory0:File = new File(downloadPath);
					var file:File = directory0.resolvePath(fileName);
					downloadFile(url, file.nativePath);
				}
				else
					Alert.show("File Already exists");
			} else {
				var directory1:File = File.documentsDirectory;
				directory1.browseForDirectory("Select Download Directory");
				directory1.addEventListener(Event.SELECT, directorySelected);
			}
		}
		
		private function directorySelected(e:Event):void {
			var directory:File = e.target as File;
			downloadPath = directory.nativePath;
			download(_url);
		}
		
		private function get downloadPath():String {
			var proxy:SettingsProxy = facade.retrieveProxy(SettingsProxy.NAME) as SettingsProxy;
			return proxy.singleDownloadPath;
		}
		
		private function set downloadPath(path:String):void {
			var proxy:SettingsProxy = facade.retrieveProxy(SettingsProxy.NAME) as SettingsProxy;
			proxy.singleDownloadPath = path;
		}
	}
}